package net.adetech.dcweb.core.dc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.adetech.dcweb.core.dc.entity.DcAlarm;
import net.adetech.dcweb.core.dc.entity.DcData;
import net.adetech.dcweb.core.dc.entity.DcInfo;
import net.adetech.dcweb.core.dc.service.IDcAlarmService;
import net.adetech.utils.UtilsCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.*;

/**
 * Created by sunfeihu on 2016/10/20.
 */
@Service
public class DcAlarmServiceImpl implements IDcAlarmService {

    private final Logger logger = LoggerFactory.getLogger(DcAlarmServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public DcAlarm save(DcAlarm entity) {
        final String sql = " insert into dc_alarm (uuid,add_user,add_date,add_ip,add_info,update_user,update_date,update_ip,update_info,info_id,alarm_date,dc_data_id,ids,is_delete) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final DcAlarm finalEntity = entity;
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, finalEntity.getUuid());
                ps.setObject(2, finalEntity.getAddUser());
                if (null != finalEntity.getAddDate()) {
                    ps.setObject(3, new java.sql.Timestamp(finalEntity.getAddDate().getTime()));
                } else {
                    ps.setObject(3, null);
                }
                ps.setObject(4, finalEntity.getAddIp());
                ps.setObject(5, finalEntity.getAddInfo());
                ps.setObject(6, finalEntity.getUpdateUser());
                if (null != finalEntity.getUpdateDate()) {
                    ps.setObject(7, new java.sql.Timestamp(finalEntity.getUpdateDate().getTime()));
                } else {
                    ps.setObject(7, null);
                }
                ps.setObject(8, finalEntity.getUpdateIp());
                ps.setObject(9, finalEntity.getUpdateInfo());
                ps.setObject(10, finalEntity.getInfoId());
                if (null != finalEntity.getAlarmDate()) {
                    ps.setObject(11, new java.sql.Timestamp(finalEntity.getAlarmDate().getTime()));
                } else {
                    ps.setObject(11, null);
                }
                ps.setObject(12, finalEntity.getDcDataId());
                ps.setObject(13, finalEntity.getIds());
                ps.setObject(14, finalEntity.getIsDelete());
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        return this.find(id);
    }

    @Override
    public void save(JSONArray array) {
        JSONObject obj = null;
        DcAlarm entity = null;
        for (int i = 0; i < array.size(); i++) {
            obj = array.getJSONObject(i);
            entity = new DcAlarm();
        }
    }

    @Override
    public int update(DcAlarm entity) {
        final String sql = " update dc_alarm set add_info=?,update_info=?,info_id=?,alarm_date=?,dc_data_id=?,ids=? where id = ?";
        return jdbcTemplate.update(sql, new Object[]{
                entity.getAddInfo(),
                entity.getUpdateInfo(),
                entity.getInfoId(),
                entity.getAlarmDate(),
                entity.getDcDataId(),
                entity.getIds(),
                entity.getId()
        });
    }

    @Override
    public DcAlarm find(Long id) {
        final String sql = " select * from dc_alarm where id = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, new DcAlarmRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void read(Long id, Long adminuserId) {
        DcAlarm entity = this.find(id);
        String ids = UtilsCommon.getString(entity.getIds());
        if (null == ids || "".equals(ids)) {
            ids = ",";
        }
        ids += adminuserId + ",";
        final String sql = " update dc_alarm set ids = ? where id = ? ";
        jdbcTemplate.update(sql, new Object[]{ids, id});
    }

    @Override
    public List<DcData> list(Integer isRead, Long adminuserId) {
        //如果是未读
        if (isRead.equals(0)) {
            final String sql = " select a.id as alarm_id,a.alarm_date,c.*,d.photo,b.man_type from dc_alarm a left join dc_info b on a.info_id = b.id and b.is_delete = 0 left join dc_data c ON a.dc_data_id = c.id left join dc_people d on d.card_no = c.card_no  where ( a.ids not like '%," + adminuserId + ",%' or a.ids is null ) and b.alarm_ids like '%,"+adminuserId+",%' order by a.id desc ";
            return jdbcTemplate.query(sql, new DcDataRowerMapper());
        } else {//如果是已读
            final String sql = " select a.id as alarm_id,a.alarm_date,c.*,d.photo,b.man_type from dc_alarm a left join dc_info b on a.info_id = b.id and b.is_delete = 0 left join dc_data c ON a.dc_data_id = c.id left join dc_people d on d.card_no = c.card_no where a.ids like '%," + adminuserId + ",%' and b.alarm_ids like '%,"+adminuserId+",%' order by a.id desc ";
            return jdbcTemplate.query(sql, new DcDataRowerMapper());
        }

    }

    @Override
    public List<DcData> list(Integer isRead, Long adminuserId, Timestamp start, Timestamp end) {

        if (isRead.equals(0)) {
            final String sql = " select a.id as alarm_id,a.alarm_date,c.*,d.photo,b.man_type from dc_alarm a left join dc_info b on a.info_id = b.id and b.is_delete = 0 left join dc_data c ON a.dc_data_id = c.id left join dc_people d on d.card_no = c.card_no  where ( a.ids not like '%," + adminuserId + ",%' or a.ids is null ) and b.alarm_ids like '%,"+adminuserId+",%' and c.buy_time > ? and c.buy_time < ? order by a.id desc ";
            return jdbcTemplate.query(sql,new Object[]{start,end}, new DcDataRowerMapper());
        } else {//如果是已读
            final String sql = " select a.id as alarm_id,a.alarm_date,c.*,d.photo,b.man_type from dc_alarm a left join dc_info b on a.info_id = b.id and b.is_delete = 0 left join dc_data c ON a.dc_data_id = c.id left join dc_people d on d.card_no = c.card_no where a.ids like '%," + adminuserId + ",%' and b.alarm_ids like '%,"+adminuserId+",%' and c.buy_time > ? and c.buy_time < ?  order by a.id desc ";
            return jdbcTemplate.query(sql,new Object[]{start,end}, new DcDataRowerMapper());
        }
    }

    @Override
    public void check() {
        //遍历所有的布控人，去比对dc_data，如果有身份证一致的，创建一条报警记录
        final String sql = " select * from dc_info where is_delete = 0 and state = 2 ";
        List<DcInfo> all = jdbcTemplate.query(sql, new DcInfoRowerMapper());
        final String sql1 = " select * from dc_data where card_no = ?  limit 0,1 ";
        final String sql2 = " select * from dc_alarm where dc_data_id = ? ";
        DcData dcData = null;
        DcAlarm dcAlarm = null;
        for (DcInfo dcInfo : all) {
            try {
                dcData = jdbcTemplate.queryForObject(sql1, new Object[]{dcInfo.getCardNo()}, new DcDataRowerMapper());
                //如果有需要报警的数据
                if (null != dcData) {
                    //判断是否已报警过
                    try {
                        dcAlarm = jdbcTemplate.queryForObject(sql2, new Object[]{dcData.getId()}, new DcAlarmRowerMapper());
                        //如果没有报过警，创建一条记录
                        if (null == dcAlarm) {
                            dcAlarm = new DcAlarm();
                            dcAlarm.setDcDataId(dcData.getId());
                            dcAlarm.setInfoId(dcInfo.getId());
                            dcAlarm.setAddDate(Calendar.getInstance().getTime());
                            dcAlarm.setAlarmDate(Calendar.getInstance().getTime());
                            dcAlarm.setIsDelete(false);
                            this.save(dcAlarm);
                        }
                    } catch (DataAccessException e1) {
                        //如果没有报过警，创建一条记录
                        dcAlarm = new DcAlarm();
                        dcAlarm.setDcDataId(dcData.getId());
                        dcAlarm.setInfoId(dcInfo.getId());
                        dcAlarm.setAddDate(Calendar.getInstance().getTime());
                        dcAlarm.setAlarmDate(Calendar.getInstance().getTime());
                        dcAlarm.setIsDelete(false);
                        dcAlarm.setUuid(UUID.randomUUID().toString());
                        this.save(dcAlarm);
                    }
                }
            } catch (DataAccessException e) {
                //如果没有报警数据
            }
        }
    }
}


class DcAlarmRowerMapper implements RowMapper<DcAlarm> {
    @Override
    public DcAlarm mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Set
                <String> fieldSet = new HashSet
                <String>();
        for (int i = 1; i <= columnCount; i++) {
            fieldSet.add(rsmd.getColumnName(i));
        }
        DcAlarm entity = new DcAlarm();
        if (fieldSet.contains("add_date") && null !=
                rs.getObject("add_date")) {
            entity.setAddDate(new
                    java.util.Date(rs.getTimestamp("add_date").getTime()));
        }
        if (fieldSet.contains("info_id") && null !=
                rs.getObject("info_id")) {
            entity.setInfoId(rs.getLong
                    ("info_id"));
        }
        if (fieldSet.contains("update_info") && null !=
                rs.getObject("update_info")) {
            entity.setUpdateInfo(rs.getString
                    ("update_info"));
        }
        if (fieldSet.contains("alarm_date") && null !=
                rs.getObject("alarm_date")) {
            entity.setAlarmDate(new
                    java.util.Date(rs.getTimestamp("alarm_date").getTime()));
        }
        if (fieldSet.contains("update_ip") && null !=
                rs.getObject("update_ip")) {
            entity.setUpdateIp(rs.getString
                    ("update_ip"));
        }
        if (fieldSet.contains("dc_data_id") && null !=
                rs.getObject("dc_data_id")) {
            entity.setDcDataId(rs.getLong
                    ("dc_data_id"));
        }
        if (fieldSet.contains("uuid") && null !=
                rs.getObject("uuid")) {
            entity.setUuid(rs.getString
                    ("uuid"));
        }
        if (fieldSet.contains("update_date") && null !=
                rs.getObject("update_date")) {
            entity.setUpdateDate(new
                    java.util.Date(rs.getTimestamp("update_date").getTime()));
        }
        if (fieldSet.contains("is_delete") && null !=
                rs.getObject("is_delete")) {
            entity.setIsDelete(rs.getBoolean
                    ("is_delete"));
        }
        if (fieldSet.contains("add_ip") && null !=
                rs.getObject("add_ip")) {
            entity.setAddIp(rs.getString
                    ("add_ip"));
        }
        if (fieldSet.contains("update_user") && null !=
                rs.getObject("update_user")) {
            entity.setUpdateUser(rs.getString
                    ("update_user"));
        }
        if (fieldSet.contains("ids") && null !=
                rs.getObject("ids")) {
            entity.setIds(rs.getString
                    ("ids"));
        }
        if (fieldSet.contains("id") && null !=
                rs.getObject("id")) {
            entity.setId(rs.getLong
                    ("id"));
        }
        if (fieldSet.contains("add_info") && null !=
                rs.getObject("add_info")) {
            entity.setAddInfo(rs.getString
                    ("add_info"));
        }
        if (fieldSet.contains("add_user") && null !=
                rs.getObject("add_user")) {
            entity.setAddUser(rs.getString
                    ("add_user"));
        }
        return entity;
    }
}